package com.data.service.impl;

import com.data.exception.LoginErr;
import com.data.model.User;
import com.data.service.LoginService;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

public class LoginServiceImpl implements LoginService {

    List<User> users = new ArrayList<>();

    @Override
    public void Register(User user, String name, String password) {
        String putName = user.getName();
        if (putName.length() > 10 || name == null || name.contains(" ")) {
            throw new LoginErr(LoginErr.ErroType.SPECIAL_UNLL);
        }
        if (!isValidPassword(password)) {
            throw new LoginErr(LoginErr.ErroType.LENGTH_ERROR);
        }
        RegisterMath(user.getName());
        for (User existingUser : users) {
            if (existingUser.getName().equals(name)) {
                throw new LoginErr(LoginErr.ErroType.NO_REPEAT_NAME);
            }
//            list.add(user);
        }
//        加密
        String encryptPassword = encryptPassword(password);
//        用户加密
        user.setEncryptedPassword(encryptPassword);
        users.add(user);

        return;
    }

    public boolean isValidPassword(String password) {
        return Pattern.matches("^(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d!@#$%^&*]{6,15}$", password);
    }


    public boolean RegisterMath(String input) {
        String regex = "^[a-zA-Z0-9]+$";
        return input.matches(regex);
    }

    private String encryptPassword(String password) throws RuntimeException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(password.getBytes());

            StringBuilder builder = new StringBuilder();

            for (byte b : digest) {
                builder.append(String.format("%02x", b));
            }
            return builder.toString();//将所有的十六进制字符串拼接成一个完整的字符串
        } catch (NoSuchAlgorithmException e) {
            throw new LoginErr(LoginErr.ErroType.MD5_PASSWORD);
        }
    }

    @Override
    public User UserLongIn(String name, String password) {
       User user = new User();
        for (User user1 : users) {
            if (!Objects.equals(user1.getName(), name)) {
                throw new RuntimeException("用户未注册");
            }
            String encryptPassword = encryptPassword(password);
//        用户加密
            user.setEncryptedPassword(encryptPassword);
            if (!Objects.equals(user1.getPassword(), encryptPassword)){
                throw new RuntimeException("用户密码错误");
            }

            System.out.println("登录成功");

        }

        users.add(user);
        return null;
    }
}
